/**
 * 
 */
package com.estock.common.model.security;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;

import org.apache.commons.lang.StringUtils;
import org.codehaus.jackson.annotate.JsonIgnore;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;

/**
 * @author richard
 * 
 */
@Entity
@Table(name="StockCategory")
@Cache(usage=CacheConcurrencyStrategy.READ_WRITE)
@JsonIgnoreProperties(ignoreUnknown=true)
public class StockCategory extends BaseEntity {

	private static final long serialVersionUID = -638770546773564065L;
	
	private String name;
	private int isActive;
	
	// do not use CascadeType.ALL, for it will delete everything.
	@ManyToMany(cascade=CascadeType.MERGE)
	@JoinTable(name="StockCatRelate",
		joinColumns={@JoinColumn(name="StockCategoryId")},
		inverseJoinColumns={@JoinColumn(name="StockId")}
	)
	@JsonIgnore
	private List<Stock> stocks = new ArrayList<Stock>();
	
	public List<Stock> getStocks() {
		return stocks;
	}

	public void setStocks(List<Stock> stocks) {
		this.stocks = stocks;
	}
	
	public void addStock(Stock stock) {
		this.getStocks().add(stock);
	}
	
	public void removeStock(Stock stock) {
		this.getStocks().remove(stock);
	}
	
	public StockCategory() {}
	
	public StockCategory(String name, int isActive) {
		this.name = name;
		this.isActive = isActive;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getIsActive() {
		return isActive;
	}

	public void setIsActive(int isActive) {
		this.isActive = isActive;
	}

	@Override
	public boolean equals(Object o) {
		if (o == null) return false;
		if (!(o instanceof StockCategory)) return false;
		
		if (this.getId() == ((StockCategory) o).getId() ||
				StringUtils.equals(this.getName(), ((StockCategory) o).getName())) {
			return true;
		}
		
		return false;
		
	}

}
